/**
 * Package	: com.coship.adstorm.common
 * File		: SysInitListener.java
 * Company 	: Shenzhen Coship Electronics CO., LTD.
 * Version  : v1.0
 * Description 	: <Detail Description for package>
 *
 * Copyright (c) 2003-2009 Shenzhen Coship Electronics CO., LTD.
 * Rainbow Bldg.,North,Hi-Tech Industrial Park,Nanshan District,Shenzhen,China,P.C.518057.
 * All rights reserved.
 * The contents of this file are confidential and proprietary to COSHIP.
 * Copying is explicitly prohibited without the express permission of COSHIP.
 *
 * Create Date	: Apr 23, 2010
 * Create By    : 904120
 * History :$
 */
package com.coship.vasms.adstorm.common;

import java.io.FileInputStream;
import java.util.Date;
import java.util.Properties;
import java.util.TimeZone;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpServlet;

import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

import com.coship.vasms.adstorm.common.log.JLogger;
import com.coship.vasms.adstorm.common.log.LoggerFactory;

/**
 * 
 * File Name : SysInitListener.java
 * 
 * @Description : 系统启动类
 * @author 904120
 */
public class SysInitListener extends HttpServlet implements
		ServletContextListener {
	/**
	 * Description : <Detail Description for package> Author : 904120
	 */
	private static final long serialVersionUID = 1L;
	private static JLogger logger = null;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent sce) {
		// 将系统缺省时区设置为亚洲上海所在的时区。
		// 在UNIX系统中，java默认采用格林尼治时间，从而导致java时间和中国北京时间相差8个小时
		System.out.println("------------系统缺省时区为"
				+ TimeZone.getDefault().getDisplayName() + "------------");
		System.out.println("------------设置系统缺省时区为Asia/Shanghai------------");
		System.out.println("当前时间" + new Date());
		TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
		System.out.println("------------系统缺省时区为"
				+ TimeZone.getDefault().getDisplayName() + "------------");
		System.out.println("当前时间" + new Date());

		try {
			ServletContextKeeper.getInstance().setServletContext(
					sce.getServletContext());
			// 取得初始化配制参数
			String configDir = sce.getServletContext().getInitParameter(
					"config_dir");
			String logRefreshTimeString = sce.getServletContext()
					.getInitParameter("logRefreshTime");
			if (configDir != null && !"".equals(configDir)) {
				CommonUtils.setConfigDir(configDir);
			}
			// 设置web.war包目录
			CommonUtils.setWebPackageDir(sce.getServletContext()
					.getRealPath("")
					+ CommonUtils.getSysFileSeparator());
			/*
			 * System.out.println("===========================================================");
			 * System.out.println("web-inf="+CommonUtils.getWebInfDir());
			 * System.out.println("===========================================================");
			 * TimeUnit.SECONDS.sleep(10);
			 */
			String confdir = CommonUtils.getConfigPath();
			System.out.println("confdir==" + confdir);
			System.out.println("catalina.home" + System.getProperty("catalina.home"));
			System.out.println("usr.dir="+CommonUtils.getUserDir());
			System.out.println("日志组件开始加载");

			int logRefreshTime = 60; // by seconds
			if (logRefreshTimeString != null
					&& !"".equals(logRefreshTimeString)) {
				logRefreshTime = Integer.parseInt(logRefreshTimeString);
			}
			LoggerFactory.configLog(confdir + CommonUtils.getSysFileSeparator()
					+ "log4j.xml", logRefreshTime);
			System.out.println("日志组件加载成功");
			logger = LoggerFactory.getLogger(SysInitListener.class);
			logger.info("log4j日志组件加载成功");

			BeanHelper.getInstance();
			// 初始化定时任务组件
			logger.info("初始化定时任务组件开始...");
			initQuartz();
			logger.info("初始化定时任务组件结束");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("系统初始化时出现错误,cause:", e);
		}
	}

	private void initQuartz() {
		String quartzProperties = "quartz.properties";
		String quartzJobConfig = "quartz_jobs.xml";
		StdSchedulerFactory factory;
		FileInputStream fin = null;
		try {
			// 获取配置文件路径
			String configPath = CommonUtils.getConfigPath()
					+ CommonUtils.getSysFileSeparator();
			System.out.println("config file path is: " + configPath);
			logger.info("config file path is: " + configPath);
			String configFile = configPath.concat(quartzProperties);

			if (configFile != null) {
				fin = new FileInputStream(configFile);
				Properties configProperties = new Properties();
				configProperties.load(fin);
				// 读取任务配置文件
				configProperties.setProperty(
						"org.quartz.plugin.jobInitializer.fileName", configPath
								+ quartzJobConfig);
				factory = new StdSchedulerFactory(configProperties);
			} else {
				factory = new StdSchedulerFactory();
			}
			Scheduler scheduler = factory.getScheduler();
			scheduler.start();
		} catch (Exception e) {
			logger.error("初始化定时任务异常： ", e);
			e.printStackTrace();
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (Exception ex) {
					fin = null;
				}
			}
		}
	}

}
